package com.diandiansong.app.ui.cart;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.diandiansong.app.R;
import com.diandiansong.app.entity.AddressInfo;
import com.diandiansong.app.entity.BuyNowObj;
import com.diandiansong.app.entity.CartSettleInfo;
import com.diandiansong.app.entity.CommodityInfoInfo;
import com.diandiansong.app.entity.cartSubmitorderInfo;
import com.diandiansong.app.ui.base.BaseAct;
import com.diandiansong.app.utils.A;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import diandiansong.library.utils.CCallBack;
import diandiansong.library.utils.ImgLoader;

/***
 * 确认订单
 */
public class OrderCheck extends BaseAct {

    static BuyNowObj mBuyNowObj;
    static List<CommodityInfoInfo.Data> mCartGoods;

    @BindView(R.id.tv_total_price)
    TextView mTvTotalPrice;
    @BindView(R.id.ll_goods)
    LinearLayout mLlGoods;
    @BindView(R.id.tv_address_name)
    TextView mTvAddressName;
    @BindView(R.id.tv_address_address)
    TextView mTvAddressAddress;
    @BindView(R.id.et_note)
    EditText mEtNote;

    CartSettleInfo mCartSettleInfo;
    @BindView(R.id.tv_ship_price)
    TextView mTvShipPrice;
    @BindView(R.id.tv_total_count)
    TextView mTvTotalCount;
    @BindView(R.id.tv_total_price_inpage)
    TextView mTvTotalPriceInpage;


    @BindView(R.id.ll_gift)
    View mViewGift;
    @BindView(R.id.tv_gift)
    TextView mTvGift;

    /**
     * 立即购买
     */
    public static void start(Context context, BuyNowObj buyNowObj) {
        mBuyNowObj = buyNowObj;
        mCartGoods = null;
        Intent starter = new Intent(context, OrderCheck.class);
        context.startActivity(starter);
    }

    public static void start(Context context, List<CommodityInfoInfo.Data> mSelected) {
        mBuyNowObj = null;
        mCartGoods = mSelected;
        Intent starter = new Intent(context, OrderCheck.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initTitle("确认订单");
        addContentView(R.layout.order_check);

        checkOrder();
    }

    /**
     * 进入界面
     * 或
     * 更换收货地址
     */
    private void checkOrder() {
        onLoading();
        String addressId = null;
        if (mAddress != null) {
            addressId = mAddress.getId();
        }
        final String finalAddressId = addressId;
        if (mBuyNowObj != null) {
            A.cartSettle(
                    null,
                    mBuyNowObj.product_sku_id,
                    "" + mBuyNowObj.goods_sum,
                    mBuyNowObj.product_id,
                    addressId,
                    new CCallBack<CartSettleInfo>() {

                        @Override
                        public void onSuccess(CartSettleInfo o) throws Exception {
                            mCartSettleInfo = o;
                            onLoaded();
                            CartSettleInfo.Data data = o.getData();
                            if (data == null) {
                                toast("程序异常");
                                return;
                            }
                            List<CartSettleInfo.Data.InfoList> infoList = data.getInfoList();
                            if (infoList == null) {
                                toast("程序异常");
                                return;
                            }
                            if (infoList.size() == 0) {
                                toast("程序异常");
                                return;
                            }
                            refreshUI();
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            onLoaded();
                            toast(msg);
                        }
                    }
            );

        } else {
            // [{'sku_sum':'8','id':'20731'},{'sku_sum':'8','id':'20732'}]
            JsonArray jsonArray = new JsonArray();
            for (CommodityInfoInfo.Data good : mCartGoods) {
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("sku_sum", good.getNum());
                jsonObject.addProperty("id", good.getCart_id());
                jsonArray.add(jsonObject);
            }
            A.cartSettle(
                    jsonArray.toString(),
                    null,
                    null,
                    null,
                    finalAddressId,
                    new CCallBack<CartSettleInfo>() {

                        @Override
                        public void onSuccess(CartSettleInfo o) throws Exception {
                            mCartSettleInfo = o;
                            onLoaded();
                            CartSettleInfo.Data data = o.getData();
                            if (data == null) {
                                toast("程序异常1");
                                return;
                            }
                            List<CartSettleInfo.Data.InfoList> infoList = data.getInfoList();
                            if (infoList == null) {
                                toast("程序异常2");
                                return;
                            }
                            if (infoList.size() == 0) {
                                toast("程序异常3");
                                return;
                            }
                            refreshUI();
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            onLoaded();
                            toast(msg);
                        }
                    }
            );
        }
    }

    private void refreshUI() {

        if (mCartSettleInfo.getData().showGift()) {
            mViewGift.setVisibility(View.VISIBLE);
            mTvGift.setText(mCartSettleInfo.getData().getGift_sum());

        } else {
            mViewGift.setVisibility(View.GONE);
        }


        CartSettleInfo.Data.AddressInfo addressInfo = mCartSettleInfo.getData().getAddressInfo();
        if (addressInfo != null) {
            setText(mTvAddressName, addressInfo.getName() + "  " + addressInfo.getMobile());
            setText(mTvAddressAddress, addressInfo.getLocation());
        }

        setText(mTvTotalPrice, "合计：￥" + mCartSettleInfo.getData().getPayAmount());
        mTvShipPrice.setText("￥" + mCartSettleInfo.getData().getCostFreight());
        mTvTotalCount.setText(mCartSettleInfo.getData().getSumTotal());
        mTvTotalPriceInpage.setText(mCartSettleInfo.getData().getOrderPayAmount());

        List<CartSettleInfo.Data.InfoList> goods = mCartSettleInfo.getData().getInfoList();
        mLlGoods.removeAllViews();
        for (int i = 0; i < goods.size(); i++) {
            CartSettleInfo.Data.InfoList item = goods.get(i);

            View view = LayoutInflater.from(getActivity()).inflate(R.layout.order_check_good_item, null);

            ImageView mIvLogo = view.findViewById(R.id.iv_logo);
            TextView mTvName = view.findViewById(R.id.tv_name);
            TextView mTvDes = view.findViewById(R.id.tv_des);
            TextView mTvPrice = view.findViewById(R.id.tv_price);
            TextView mTvCount = view.findViewById(R.id.tv_count);

            ImgLoader.display(mIvLogo, item.getImgs());
            setText(mTvName, item.getGoodsTitle());
            setText(mTvDes, item.getSkuProductText());
            setText(mTvPrice, "￥" + item.getSkuPrice());
            setText(mTvCount, "x" + item.getSkuSum());

            mLlGoods.addView(view);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    String mOrderId;

    @OnClick(R.id.do_go_pay)
    public void onViewClicked() {
        if (mOrderId != null) {
            Pay.start(getActivity(), mOrderId);
            return;
        }
        String addrId = null;
        try {
            addrId = mCartSettleInfo.getData().getAddressInfo().getAddrId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (addrId == null) {
            toast("请选择收货地址");
            return;
        }


        onLoading();

        //提交订单
        JsonObject od = new JsonObject();
        od.addProperty("provider_id", mCartSettleInfo.getData().getProviderId());
        od.addProperty("cost_freight", mCartSettleInfo.getData().getCostFreight());
        od.addProperty("note", getText(mEtNote));

        JsonArray goods = new JsonArray();

        List<CartSettleInfo.Data.InfoList> infoList = mCartSettleInfo.getData().getInfoList();
        for (int i = 0; i < infoList.size(); i++) {
            CartSettleInfo.Data.InfoList item = infoList.get(i);

            JsonObject good = new JsonObject();
            good.addProperty("product_id", item.getGoodsId());
            good.addProperty("cart_id", item.getCartId());
            good.addProperty("product_sku_id", item.getSkuProductId());
            good.addProperty("number", "" + item.getSkuSum());
            goods.add(good);

            od.add("goods_info", goods);
        }


        A.cartSubmitorder(addrId, od.toString(), new CCallBack<cartSubmitorderInfo>() {
            @Override
            public void onSuccess(cartSubmitorderInfo o) throws Exception {
                onLoaded();
                mOrderId = o.getData();
                Pay.start(getActivity(), mOrderId);
                finish();
            }

            @Override
            public void onFailure(int code, String msg) {
                onLoaded();
                toast(msg);
            }
        });
    }

    @OnClick(R.id.go_address)
    public void onViewClickedAddress() {
        AddressChoose.start(getActivity());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //更换收货地址，刷新订单价格
        if (AddressChoose.onActivityResultAddressChoose(requestCode, resultCode, data)) {
            if (AddressChoose.mAddress != null) {
                mAddress = AddressChoose.mAddress;
                setText(mTvAddressName, mAddress.getNames() + "  " + mAddress.getMobile());
                setText(mTvAddressAddress, mAddress.getArea() + mAddress.getAddr());

                checkOrder();
            }
        }
    }

    AddressInfo.Data mAddress;


    public static class Finish {
    }

    /**
     * 支付完成后关闭订单界面
     */
    public static void doFinish() {
        EventBus.getDefault().post(new Finish());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveFinish(Finish finish) {
        finish();
    }
}
